package com.blb.utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 生成验证码的Servlet
 * @author Administrator
 *
 */
@Controller

public class CodeUtils extends HttpServlet{

    //包含所有字母和数字的字符串
    private static final String CODES = "ABCDEFHIJKLMNPQRSTUVWXY3456789";
    //图片的宽
    private static final int WIDTH = 90;
    //图片的高
    private static final int HEIGHT = 30;
    //字体大小
    private static final int FONT_SIZE = 20;
    private static final Color[] COLORS = {Color.RED,Color.BLACK,Color.BLUE,Color.CYAN,Color.GREEN,Color.MAGENTA,
            Color.ORANGE,Color.PINK,Color.YELLOW,Color.WHITE};
    @Override
    @RequestMapping("code")
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //创建缓冲图片
        BufferedImage image = new BufferedImage(WIDTH,HEIGHT,BufferedImage.TYPE_INT_ARGB);
        //获得图片的图形对象
        Graphics graphics = image.getGraphics();
        //设置颜色作为背景
        graphics.setColor(Color.GRAY);
        graphics.setFont(new Font("宋体",Font.PLAIN,FONT_SIZE));
        //填充矩形
        graphics.fillRect(0, 0, WIDTH, HEIGHT);
        Random random = new Random();
        StringBuilder strb = new StringBuilder();
        //绘制4个随机的字母或数字
        for(int i = 0;i < 4;i++){
            graphics.setColor(COLORS[random.nextInt(COLORS.length)]);
            //获得随机字符
            char c = CODES.charAt(random.nextInt(CODES.length()));
            //拼接字符
            strb.append(c);
            //绘制字符
            graphics.drawString(String.valueOf(c), 10 + FONT_SIZE * i, 20);
            //绘制随机线条
//            graphics.setColor(COLORS[random.nextInt(COLORS.length)]);
//            graphics.drawLine(random.nextInt(WIDTH), random.nextInt(HEIGHT),
//                    random.nextInt(WIDTH), random.nextInt(HEIGHT));
        }
        //保存到Session中
        //不区分大小写
        req.getSession().setAttribute("code", strb.toString().toLowerCase());

        //通过IO流向浏览器发送图片
        ImageIO.write(image, "PNG", resp.getOutputStream());
    }
}
